﻿using System;
using System.Collections.Generic;

namespace Ornament.MemberShip.Permissions
{
    public class OperatorResourceMapping
    {
        private const string NHProxyType =
            "{0}Proxy, {0}ProxyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";

        private Dictionary<string, Type> _resourceMappingProxy;

        public Dictionary<Type, Type> ResourceMapping { get; set; }

        public Dictionary<string, Type> TypeResourceMapping { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private Dictionary<string, Type> ResourceMappingProxy
        {
            get { return _resourceMappingProxy ?? (_resourceMappingProxy = new Dictionary<string, Type>()); }
        }

        public Type this[Type resourceType]
        {
            get
            {
                if (ResourceMapping.ContainsKey(resourceType))
                    return ResourceMapping[resourceType];
                if (ResourceMappingProxy.Count != ResourceMapping.Count)
                {
                    BuildTheProxyMapping();
                }

                if (ResourceMappingProxy.ContainsKey(resourceType.AssemblyQualifiedName))
                {
                    return ResourceMappingProxy[resourceType.AssemblyQualifiedName];
                }

                throw new OrnamentException("Can't find operator type which belong to " + resourceType.FullName +
                                            ", it may be setting in WebCfg.config and resolve by IoC framework.");
            }
        }

        public Type this[string resourceKey]
        {
            get { return TypeResourceMapping[resourceKey]; }
        }

        private void BuildTheProxyMapping()
        {
            foreach (Type key in ResourceMapping.Keys)
            {
                ResourceMappingProxy.Add(String.Format(NHProxyType, key.Name), ResourceMapping[key]);
            }
        }
    }
}